package com.chuji.crmcj.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.ClientDetailAct;
import com.chuji.crmcj.bean.MagFollowClientInfo;
import com.chuji.crmcj.utils.NumberUtils;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

import java.util.ArrayList;
import java.util.List;

public class MagClientFollowFragment extends Fragment {
    //客户姓名
    private TextView mTv_client_name;
    //客户号码
    private TextView mTv_client_phoneNumber;
    //客户意向车型
    private TextView mTv_intent_car_type;
    //电话联系时间
    private TextView mTv_communicate_time;
    //播放录音
    private ImageButton mBtn_play;
    //客户试驾详细信息
    private TextView mTv_try_information;
    /*跟进记录网络存储*/
    private List<MagFollowClientInfo.ApiParamObjEntity> magFollowClientData;
    /*跟进记录数据*/
    private MagFollowClientInfo magFollowClientInfo;
    /*通知布局*/
    private ExpandableListView lv_follow_table;
    /*自定义适配器*/
    private CustomFollowTableAdapter customFollowTableAdapter;
//    private String musicName = "aizaixiyuanqian.mp3";
    private MediaPlayer mediaPlayer=null;
//    private ImageView mIv_cancel;
//
//    private ImageView mIv_play;
    private SeekBar mSb_detail_play_progress;
    private TextView mTv_play_time;
    private TextView mTv_total_time;
//    private boolean iffirst = false;
//    private boolean ifPlaying = true;
    //播放按钮的播放或者停止标志位  0为没有播放，1为开始播放，2为停止播放
    private int goOrPause=0;
//    //是否手动拖动播放条标志位
//    private boolean isChanging = false;//互斥变量，防止定时器与SeekBar拖动时进度冲突
//    //volatile是每次只能有一个线程来修改此值
//    private volatile Boolean isStop=false;
//    private volatile Boolean isThreadStop=false;
    //销售员ID
    String SalesID;
    //用户ID
    String UserID;
    //意图
    Intent intent;
    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mag_client_follow, container, false);
        //初始化数据
        mTv_client_name = (TextView) view.findViewById(R.id.tv_client_name);
        mTv_client_phoneNumber = (TextView) view.findViewById(R.id.tv_client_phoneNumber);
        mTv_intent_car_type = (TextView) view.findViewById(R.id.tv_intent_car_type);
        mTv_communicate_time = (TextView) view.findViewById(R.id.tv_communicate_time);
        mBtn_play = (ImageButton) view.findViewById(R.id.btn_play);
        mTv_try_information = (TextView) view.findViewById(R.id.tv_try_information);
        lv_follow_table = (ExpandableListView) view.findViewById(R.id.lv_follow_table);
        //获取ID
        SalesID=getActivity().getIntent().getStringExtra("SalesID");
        UserID=SPUtils.getString(UIUtils.getContext(),"UserID","");
        mediaPlayer = new MediaPlayer();
        //将所有项设置成默认展开
        int groupCount = lv_follow_table.getCount();
        for (int i = 0; i < groupCount; i++) {

            lv_follow_table.expandGroup(i);

        }
        ;
        lv_follow_table.setGroupIndicator(null);
        //请求数据
        getFollowUpNotes();
        return view;
    }
    /**
     * 获取跟进记录信息
     */
    private void getFollowUpNotes() {
        if(magFollowClientData==null){
            magFollowClientData=new ArrayList<MagFollowClientInfo.ApiParamObjEntity>();
        }
        //初始化Volley
        String strURL = String.format(UrlUtils.GET_MAG_FOLLOW_CLIENT+"&UserID="+UserID+"&SalesID="+SalesID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                magFollowClientInfo = JSON.parseObject(response, MagFollowClientInfo.class);
                magFollowClientData.addAll(magFollowClientInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断adapter是否创建
                        if (customFollowTableAdapter == null) {
                            //创建适配器
                            customFollowTableAdapter=new CustomFollowTableAdapter();
                            //填充数据
                            lv_follow_table.setAdapter(customFollowTableAdapter);
//                            //将所有项设置成默认展开
//                            int groupCount = lv_follow_table.getCount();
//
//                            for (int i=0; i<groupCount; i++) {
//
//                                lv_follow_table.expandGroup(i);
//
//                            };
//                            lv_follow_table.setGroupIndicator(null);
                        } else {
                            customFollowTableAdapter.notifyDataSetChanged();
                        }
                        //给ListView设置点击事件
                        lv_follow_table.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                            @Override
                            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                                intent=new Intent(UIUtils.getContext(), ClientDetailAct.class);
                                intent.putExtra("C",magFollowClientData.get(i1).getCustomerID());
                                startActivity(intent);
                                return false;
                            }
                        });
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    /**
     * 客户跟进适配器
     */
    class CustomFollowTableAdapter extends BaseExpandableListAdapter {
        private TextView mTv_follow_time;
        private LinearLayout mLl_table_content;
        private TextView mTv_client_name;
        private TextView mTv_intent_car_type;
        private TextView mTv_client_phoneNumber;
        private TextView mTv_follow_title;
        private ImageView mIv_paly;
        private TextView mTv_communicate_time;
        private TextView mTv_try_information;
        private TextView tv_car_type;
        @Override
        public int getGroupCount() {
            return magFollowClientData.size();
        }

        @Override
        public int getChildrenCount(int i) {
            return magFollowClientData.size();
        }

        @Override
        public Object getGroup(int i) {
            return magFollowClientData.get(i);
        }

        @Override
        public Object getChild(int i, int i1) {
            return magFollowClientData.get(i);
        }

        @Override
        public long getGroupId(int i) {
            return i;
        }

        @Override
        public long getChildId(int i, int i1) {
            return i1;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
            view = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.mag_listview_client_follow, null);
            mTv_follow_time = (TextView) view.findViewById(R.id.tv_follow_time);
            view.setClickable(true);
            if(magFollowClientData.size()!=0){
                mTv_follow_time.setText(magFollowClientData.get(i).getCreateTime());
            }else{
                UIUtils.showToastSafe("暂无数据");
            }
            return view;
        }

        @Override
        public View getChildView(int i, final int i1, boolean b, View convertView, ViewGroup viewGroup) {
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.mag_listview_client_one_follow, null);
                //初始化组件
                mTv_intent_car_type = (TextView) convertView.findViewById(R.id.tv_intent_car_type);
                mTv_follow_title = (TextView) convertView.findViewById(R.id.tv_follow_title);
                mLl_table_content = (LinearLayout) convertView.findViewById(R.id.ll_table_content);
                mTv_client_name = (TextView) convertView.findViewById(R.id.tv_client_name);
                mTv_intent_car_type = (TextView) convertView.findViewById(R.id.tv_intent_car_type);
                mTv_client_phoneNumber = (TextView) convertView.findViewById(R.id.tv_client_phoneNumber);
                mIv_paly = (ImageView) convertView.findViewById(R.id.iv_paly);
                mTv_communicate_time = (TextView) convertView.findViewById(R.id.tv_communicate_time);
                mTv_try_information = (TextView) convertView.findViewById(R.id.tv_try_information);
                tv_car_type= (TextView) convertView.findViewById(R.id.tv_car_type);
            } else {

            }
            if(magFollowClientData.size()!=0) {
                mTv_client_name.setText(magFollowClientData.get(i1).getName());
                if (magFollowClientData.get(0).getTel().length()==11) {
                    mTv_client_phoneNumber.setText(NumberUtils.parsePhoneNumber(magFollowClientData.get(0).getTel()));
                }else{
                    mTv_client_phoneNumber.setText(magFollowClientData.get(0).getTel());
                }
                mTv_follow_title.setText(magFollowClientData.get(0).getTaskTypeContent());
                mTv_communicate_time.setText(magFollowClientData.get(0).getCreateTime());
                tv_car_type.setText(magFollowClientData.get(0).getCarModelTile());
                mTv_intent_car_type.setText(magFollowClientData.get(0).getCarModel());
                //跟客户沟通的内容
                mTv_try_information.setText(magFollowClientData.get(0).getTaskDetail());
                mIv_paly.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showPlayRecorderDialog(magFollowClientData.get(0).getAttachment());
                    }
                });
            }else{
                UIUtils.showToastSafe("暂无数据");
            }
            return convertView;
        }
        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }
    }

    //播放录音的dialog
    public void showPlayRecorderDialog(final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final AlertDialog dialog = builder.create();
        View view = View.inflate(getContext(), R.layout.dialog_play_recorder, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
//        ImageView mIv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);
        LinearLayout ll_cancel= (LinearLayout) view.findViewById(R.id.ll_cancel);
        mBtn_play = (ImageButton) view.findViewById(R.id.btn_play);
        mSb_detail_play_progress = (SeekBar) view.findViewById(R.id.sb_detail_play_progress);
        mTv_play_time = (TextView) view.findViewById(R.id.tv_play_time);
        mTv_total_time = (TextView) view.findViewById(R.id.tv_total_time);
        mSb_detail_play_progress.setEnabled(false);
        //播放进度条
        mSb_detail_play_progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                if (fromUser==true) {
                    mediaPlayer.seekTo(progress);
                    mTv_play_time.setText(ShowTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {


            }
        });
        //退出播放
        ll_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mediaPlayer.stop();
            }
        });
        //点击播放
        mBtn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(goOrPause==0){
                    play(url);
                    mTv_play_time.setText(ShowTime(mSb_detail_play_progress.getProgress()));
                    int Alltime = mediaPlayer.getDuration();
                    mTv_total_time.setText(ShowTime(Alltime));
                    goOrPause=1;
                }
                else if(goOrPause==1||goOrPause==2){
                    pause();

                }
            }
        });
        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }
    //当音乐播放时，每次按键时都会播放或者停止音乐
    private void pause() {
        //if(bt_pause.getText().toString().trim().equals("继续")){
        if(goOrPause==2){
            mediaPlayer.start();
            goOrPause=1;
            mBtn_play.setBackgroundResource(R.drawable.zanting);
            return;
        }
        else if(goOrPause==1){
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                goOrPause=2;
                mBtn_play.setBackgroundResource(R.drawable.bofang);
            }
            else{
                UIUtils.showToastSafe("请先播放音频");
            }
        }
    }
    private void play(String url) {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource("/sdcard/test.mp3");
            mediaPlayer.prepare();
            mediaPlayer.start();
            StrartbarUpdate();
            mSb_detail_play_progress.setMax(mediaPlayer.getDuration());
            mSb_detail_play_progress.setEnabled(true);
            mBtn_play.setBackgroundResource(R.drawable.zanting);
            //音乐播放时事件
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    mBtn_play.setEnabled(true);
                }
            });
            //出错时的事件
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mBtn_play.setEnabled(true);
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            UIUtils.showToastSafe("播放失败");
        }
    }
    //时间显示函数,我们获得音乐信息的是以毫秒为单位的，把把转换成我们熟悉的00:00格式
    private String ShowTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int hour = minute / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

    Handler handler = new Handler();

    private  void StrartbarUpdate() {
        handler.post(r);
    }
    Runnable r = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            int CurrentPosition = mediaPlayer.getCurrentPosition();
            mTv_play_time.setText(ShowTime(CurrentPosition));
            mSb_detail_play_progress.setProgress(CurrentPosition);
            handler.postDelayed(r, 100);
        }
    };
}